// https://leetcode.cn/problems/palindrome-linked-list/?envType=study-plan-v2&envId=top-100-liked
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == nullptr) return false;
        if(head -> next == nullptr) return true;
        ListNode* temp = head;
        int n = 1;
        while(temp->next != nullptr) {
            temp = temp -> next;
            n++;
        }
        int mid = n / 2;
        ListNode* l = head;
        ListNode* r = head;
        ListNode* pre = nullptr;
        while(mid--) {
            ListNode* next = l -> next;
            l -> next = pre;
            pre = l;
            l = next;
        }
        if(n % 2 != 0) {
            r = l -> next;
            l = pre;
            
        }else {
            r = l;
            l = pre;
        }
        
        while(r != nullptr && l != nullptr) {
            if(r -> val != l -> val) {
                return false;
            }
            r = r -> next;
            l = l -> next;
        }
        return true;
    }
};